/*   
 * Copyright 2009-2010 Rob Schoening
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *    
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.beaconframework.vaadin.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;

import org.beaconframework.util.ThreadContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Application Lifecycle Listener implementation class RequestContextListener
 * 
 */
public class RequestContextListener extends
        org.springframework.web.context.request.RequestContextListener
        implements ServletRequestListener {
    /**
     * @see org.springframework.web.context.request.RequestContextListener#org.springframework.web.context.request.RequestContextListener()
     */
    public RequestContextListener() {
        super();

    }

    @Override
    public void requestDestroyed(ServletRequestEvent requestEvent) {

        super.requestDestroyed(requestEvent);
        ThreadContext.unbindThread();
    }

    @Override
    public void requestInitialized(ServletRequestEvent requestEvent) {

        super.requestInitialized(requestEvent);

        ThreadContext ctx = new ThreadContext();
        ctx.put(ServletContext.class, requestEvent.getServletContext());
        ctx.put(ApplicationContext.class, WebApplicationContextUtils
                .getRequiredWebApplicationContext(requestEvent
                        .getServletContext()));
        ctx.put(HttpServletRequest.class, requestEvent.getServletRequest());

        ctx.bindThread();
    }

}
